package cn.ebook.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

/**
 * 连接数据库工具类
 * 
 * @author 洋洋洋.
 * @date 2018-7-27 1:44.
 */
public class BaseUtil {

	private static Connection connection;
	private static PreparedStatement pStatement;
	/**
	 * 静态代码块加载驱动
	 * 
	 * @author 洋洋洋.
	 * @date 2018-7-27 1:44.
	 * 
	 */
	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取connection常规
	 * 
	 * @author 洋洋洋.
	 * @date 2018-7-27 1:49
	 * @return connection
	 * @throws SQLException
	 */
	public static Connection getConnection() throws SQLException {
		// Drivermanager类确定联的是哪种数据库。
		return DriverManager.getConnection("jdbc:mysql://localhost:3306/ebook", "root", "P@ssW0rd");
	}

	/**
	 * jndi获取connection
	 * 
	 * @return connection
	 * @throws SQLException
	 * @throws NamingException
	 */
	public static Connection getConnection1() throws SQLException, NamingException {
		Context con;
		con = new InitialContext();
		DataSource dt = (DataSource) con.lookup("java:comp/env/ebook");
		Connection conn = dt.getConnection();
		return conn;
	}

	/**
	 * 通用增删改
	 * 
	 * @param obj
	 *            可变参用来填补占位符
	 * @param sql
	 *            sql语句
	 * @return 受影响行数
	 * @throws SQLException
	 * @special 用了可变参数
	 */
	public static int addOrDelOrSet(String sql, Object... obj) throws SQLException {
		connection = BaseUtil.getConnection();
		pStatement = connection.prepareStatement(sql);
		for (int i = 0; i < obj.length; i++) {
			pStatement.setObject(i + 1, obj[i]);
		}
		int source = pStatement.executeUpdate();
		BaseUtil.closeAll(null, connection, pStatement);
		return source;
	}

	/**
	 * 关闭资源
	 * 
	 * @param rSet
	 *            resultSet
	 * @param connection
	 *            Connection
	 * @param pStatement
	 *            Statement
	 * @throws SQLException
	 */
	public static void closeAll(ResultSet rSet, Connection connection, Statement pStatement) throws SQLException {
		if (rSet != null) {
			rSet.close();
		}
		if (pStatement != null) {
			pStatement.close();
		}
		if (connection != null) {
			connection.close();
		}
	}

}
